<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title></title>
        <link rel="stylesheet" type="text/css" href="../../../css/aui.css" />
        <script src="../../../script/jquery.js"></script>
        <script src="../../../CommonTool/commonNetWork.js"></script>
    </head>
    <style>
    html, body {
      margin: 0;
      padding: 0;
      height: 100%;
    }

    body {
      background-image: url('1.png'); /* 替换为你的图片地址 */
      background-size: cover;         /* ✅ 图片按比例缩放填满屏幕 */
      background-position: center;    /* ✅ 居中显示图片 */
      background-repeat: no-repeat;   /* ✅ 不重复平铺 */
      background-attachment: fixed;   /* 可选：背景随页面固定 */
    }
    </style>
    <body>
            <div class="aui-row">
                <div class="aui-col-xs-4"></div>
                <div class="aui-col-xs-4">
                    <div class="aui-btn aui-btn-primary StyleButton" id="SightstartButton">开始录制</div>
                    <div class="aui-btn aui-btn-primary StyleButton" id="SightstopButton" style="display: none">
                        结束录制
                    </div>
                </div>
    </body>
</html>
<script>
    var isRecording = true;
    var token = "";
    var userid = "";
    var currentTimestamp = "";
    var operationName = "";
    var additionalInfo = "";
    var groupId = "";
    var scene = "基础";
    var sceneLevel = "初级";
    var courseType = "视线训练";
    var classSort = "1";
    var remarks = "视线定位";
    var startButton = document.getElementById("SightstartButton");
    var stopButton = document.getElementById("SightstopButton");
    let mediaRecorder;
    let chunks = [];
    let blob;
    let videoStream;
    var Nowdate = "";
    var NowdateString = "";
    let SightfileName = "";
    apiready = function () {
        token = api.pageParam.token;
        userid = api.pageParam.uid;
        isRecording = true;
        groupId = api.pageParam.groupId;
        currentTimestamp = Date.now();
        operationName = "ing";
        additionalInfo = "";
        if (api.pageParam.haved == "haved") {
            groupId = api.pageParam.groupId;
        } else {
            InitializeCommonNetWork();
        }
        //      let index = 0;
        // const interval = setInterval(() => {
        //   if (index < textToAnimate.length) {
        //     // 创建一个新的span元素来包裹每个字
        //     const charSpan = document.createElement('span');
        //     charSpan.textContent = textToAnimate[index];
        //     // 添加跳动动画类名
        //     charSpan.classList.add('jump-animation');
        //     // 将包含字的span元素添加到textDisplay中
        //     textDisplay.appendChild(charSpan);
        //     index++;
        //   } else {
        //     clearInterval(interval);
        //   }
        // },200); // 可以调整这个时间间隔来控制跳动速度
    };
    //底部
    function InitialClick() {
        document.getElementById("InitialButton").style.display = "none";
        document.getElementById("InitialButton1").style.display = "block";
        document.getElementById("InitialButton4").style.display = "block";
    }
    function ShowInitialClick() {
        document.getElementById("InitialButton").style.display = "block";
        document.getElementById("InitialButton1").style.display = "none";
        document.getElementById("InitialButton4").style.display = "none";
    }
    function ResetClick() {
        history.go(0);
    }
    function go_forward() {
        currentTimestamp = Date.now();
        operationName = "end";
        additionalInfo = "right";
        CommonNetWork();
        if (mediaRecorder && mediaRecorder.state !== "inactive") {
            mediaRecorder.stop();
        }
        api.openWin({
            name: "SightTraining2",
            url: "./SightTraining2.html",
            pageParam: {
                uid: userid,
                token: token,
                groupId: groupId,
            },
            reload: true,
        });
    }
    //表情模仿的录制视频
    async function getMediaStream() {
        const hasCameraPermission = hasPermissionObj("camera");
        const hasMicrophonePermission = hasPermissionObj("microphone");
        if (!hasCameraPermission || !hasCameraPermission[0] || !hasCameraPermission[0].granted) {
            api.confirm(
                {
                    title: "提醒",
                    msg: "没有获得 " + "相机" + " 权限\n是否前往设置？",
                    buttons: ["去设置", "取消"],
                },
                function (ret, err) {
                    if (1 == ret.buttonIndex) {
                        reqPermission("camera");
                        history.go(0);
                    }
                }
            );
            return false;
        } else if (!hasMicrophonePermission || !hasMicrophonePermission[0] || !hasMicrophonePermission[0].granted) {
            api.confirm(
                {
                    title: "提醒",
                    msg: "没有获得 " + "麦克风" + " 权限\n是否前往设置？",
                    buttons: ["去设置", "取消"],
                },
                function (ret, err) {
                    if (1 == ret.buttonIndex) {
                        reqPermission("microphone");
                        history.go(0);
                    }
                }
            );
            return false;
        } else {
            // 已授予权限，直接获取媒体流
            videoStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "user", width: 1920, height: 1080 }, audio: false });
            mediaRecorder = new MediaRecorder(videoStream);
            return videoStream;
        }
    }
    // 开始录制
    startButton.addEventListener("click", async () => {
        alert("开始录制");
        setTimeout(() => {
        }, 4000);
        startButton.style.display = "none";
        stopButton.style.display = "block";
        videoStream = await getMediaStream();
        if (videoStream) {
            mediaRecorder.start();
            mediaRecorder.ondataavailable = (event) => {
                if (event.data.size > 0) {
                    chunks.push(event.data);
                }
            };
        }
        //开始录制这里获取时间
        Nowdate = new Date();
        const year = Nowdate.getUTCFullYear();
        const month = (Nowdate.getUTCMonth() + 1).toString().padStart(2, "0"); // 月份从0开始，所以加1
        const day = Nowdate.getUTCDate().toString().padStart(2, "0");
        const hours = (Nowdate.getUTCHours() + 8).toString().padStart(2, "0");
        const minutes = Nowdate.getUTCMinutes().toString().padStart(2, "0");
        const seconds = Nowdate.getUTCSeconds().toString().padStart(2, "0");
        // 组合成字符串
        NowdateString = `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;
        //切换到结束录制按钮
        isRecording = false;
    });
    // 停止录制并处理录制数据
    stopButton.addEventListener("click", () => {
        mediaRecorder.stop();
        mediaRecorder.onstop = () => {
            blob = new Blob(chunks, { type: "video/mp4" });
            // 上传视频数据
            uploadVideo(blob);
            chunks = [];
            isRecording = true;
            startButton.style.display = "block";
            stopButton.style.display = "none";
        };
    });
    function uploadVideo(blob) {
        const blobChunk = blob;
        var chunkSize = 1024 * 1024;
        let start = 0; // 从0开始切片
        let count = 1; //从1开始
        var totalPieces = Math.ceil(blobChunk.size / chunkSize); //总数

        while (start < blobChunk.size) {
            var end = start + chunkSize;
            if (end > blobChunk.size) {
                //小于1M也传
                end = blobChunk.size;
            }
            uploadChunk(blobChunk.slice(start, end), count, totalPieces);
            start += chunkSize;
            count++;
        }
    }
    function uploadChunk(chunk, count, totalPieces) {
        ImitatefileName =
            userid +
            "—" +
            scene +
            "—" +
            sceneLevel +
            "—" +
            courseType +
            "—" +
            classSort +
            "—" +
            groupId +
            "—" +
            NowdateString +
            ".mp4";
        var formData = new FormData();
        formData.append("audioFile", chunk);
        formData.append("sliceNumber", count);
        formData.append("totalSlices", totalPieces);
        formData.append("fileName", ImitatefileName);
        formData.append("userid", userid);
        // 使用原生的fetch API示例（可替换为XMLHttpRequest等方式）
        fetch(CommonUrl + "/test/uploadSlice", {
            method: "post",
            headers: {
                Authorization: `Bearer ${token}`,
            },
            body: formData,
        })
            .then((res) => {
                // 上传成功后的处理
                alert("上传成功");
                // alert(JSON.stringify(res));
            })
            .catch((res) => {
                // 上传失败后的处理
                alert("上传失败");
                // alert(JSON.stringify(res));
            });
    }
    //上传本地视频的时候用到这个方法
    function CallVideo() {
        var has = hasPermissionObj("storage");
        if (!has || !has[0] || !has[0].granted) {
            api.confirm(
                {
                    title: "提醒",
                    msg: "没有获得 " + "本地存储" + " 权限\n是否前往设置？",
                    buttons: ["去设置", "取消"],
                },
                function (ret, err) {
                    if (1 == ret.buttonIndex) {
                        reqPermission("storage");
                    }
                }
            );
            return false;
        }
    }
    function reqPermission(one_per, callback) {
        var perms = new Array();
        if (one_per) {
            perms.push(one_per);
        }
        api.requestPermission(
            {
                list: perms,
                code: 100001,
            },
            function (ret, err) {
                if (callback) {
                    callback(ret);
                    return;
                }
                var str = "请求结果：\n";
                str += "请求码: " + ret.code + "\n";
                str += '是否勾选"不再询问"按钮: ' + (ret.never ? "是" : "否") + "\n";
                str += "请求结果: \n";
                var list = ret.list;
                for (var i in list) {
                    str += list[i].name + "=" + list[i].granted + "\n";
                }
                console.log(JSON.stringify(ret));
            }
        );
    }

    function close_win() {
        api.openWin({
            name: "SubsetMenu-Basics",
            url: "../../SubsetMenu-Basics.html",
            reload: true,
        });
    }
    function ResetClick2() {
        api.openWin({
            name: "SightTraining1",
            url: "./SightTrainingOnee.html",
            pageParam: {
                uid: userid,
                token: token,
                groupId: groupId,
            },
            reload: true,
            animation: {
                type: "none", // 禁用动画类型
                duration: 0, // 动画时长设为0
            },
        });
    }
    function goto_page(number) {
        const pages = ["SightTraining1", "SightTraining2", "SightTraining3", "SightTraining4","SightTraining5"];

        var name = pages[number - 1];
        var url = "./" + name + ".html";

        document.querySelectorAll("audio").forEach((audio) => audio.pause());

        currentTimestamp = Date.now();
        operationName = "end";
        additionalInfo = "";
        CommonNetWork();
        api.openWin({
            name: name,
            url: url,
            pageParam: {
                uid: userid,
                token: token,
                groupId: groupId,
            },
            reload: true,
        });
    }
    function toggleMenu() {
        var menu = document.getElementById("menu");
        if (menu.style.display === "none" || menu.style.display === "") {
            menu.style.display = "block";
        } else {
            menu.style.display = "none";
        }
    }
</script>
